package com.shitou.springai1.user.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shitou.springai1.user.entity.IntentResult;
import com.shitou.springai1.user.entity.IntentType;
import com.shitou.springai1.user.entity.ParsedQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

// SemanticParserService.java
@Service
@Slf4j
public class SemanticParserService {

    @Autowired
    private IntentRecognitionService intentRecognitionService;

    @Autowired
    private ChineseSegmentService segmentService;

    public ParsedQuery parseQuery(String userInput) {
        log.info("开始语义解析: {}", userInput);

        try {
            // 第一步：意图识别
            IntentResult intentResult = intentRecognitionService.analyzeIntent(userInput);

            // 第二步：提取搜索关键词
            List<String> searchKeywords = extractSearchKeywords(intentResult);

            // 第三步：构建解析结果
            ParsedQuery parsedQuery = new ParsedQuery();
            parsedQuery.setOriginalInput(userInput);
            parsedQuery.setIntent(intentResult.getPrimaryIntent());
            parsedQuery.setEntities(intentResult.getEntities());
            parsedQuery.setSearchKeywords(searchKeywords);
            parsedQuery.setContainsLocationQuery(
                intentResult.getPrimaryIntent() == IntentType.LOCATION_QUERY);
            parsedQuery.setConfidence(intentResult.getConfidence());

            log.info("语义解析完成: {}", parsedQuery);
            return parsedQuery;

        } catch (Exception e) {
            log.error("语义解析失败: {}", userInput, e);

            ParsedQuery errorResult = new ParsedQuery();
            errorResult.setOriginalInput(userInput);
            errorResult.setIntent(IntentType.UNKNOWN);
            errorResult.setEntities(new HashMap<>());
            errorResult.setSearchKeywords(segmentService.extractKeywords(userInput));
            errorResult.setContainsLocationQuery(false);
            errorResult.setConfidence(0.0);
            errorResult.setErrorMessage("解析失败: " + e.getMessage());

            return errorResult;
        }
    }

    private List<String> extractSearchKeywords(IntentResult intentResult) {
        List<String> keywords = new ArrayList<>();

        // 使用重写后的查询进行分词
        if (StringUtils.isNotBlank(intentResult.getRewrittenQuery())) {
            keywords = segmentService.extractKeywords(intentResult.getRewrittenQuery());
        } else {
            keywords = segmentService.extractKeywords(intentResult.getOriginalQuery());
        }

        // 根据意图类型优化关键词
        return optimizeKeywords(keywords, intentResult.getPrimaryIntent());
    }

    private List<String> optimizeKeywords(List<String> keywords, IntentType intent) {
        if (intent == IntentType.LOCATION_QUERY) {
            // 对于位置查询，优先保留包含建筑、房间等信息的词
            return keywords.stream()
                    .sorted((a, b) -> {
                        boolean aIsLocation = a.contains("楼") || a.contains("室") || a.matches(".*\\d+.*");
                        boolean bIsLocation = b.contains("楼") || b.contains("室") || b.matches(".*\\d+.*");
                        if (aIsLocation && !bIsLocation) return -1;
                        if (!aIsLocation && bIsLocation) return 1;
                        return 0;
                    })
                    .collect(Collectors.toList());
        }

        return keywords;
    }
}
